package it.itsvil.ejb.mdb;

import java.io.File;
import java.io.IOException;

import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.ejb.EJBException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;
import javax.xml.transform.stream.StreamSource;

import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.Serializer;
import net.sf.saxon.s9api.XQueryCompiler;
import net.sf.saxon.s9api.XQueryEvaluator;
import net.sf.saxon.s9api.XQueryExecutable;

public class SimpleTopicXQuery implements MessageDrivenBean, MessageListener {
	private MessageDrivenContext ctx = null;

	public SimpleTopicXQuery() {

	}

	public void setMessageDrivenContext(MessageDrivenContext ctx) {
		this.ctx = ctx;
	}

	public void ejbCreate() {
	}

	public void ejbRemove() {
	}

	public void onMessage(Message msg) {
		ObjectMessage om = (ObjectMessage) msg;
		try {
			Processor proc = new Processor(false);
			XQueryCompiler comp = proc.newXQueryCompiler();
			String filePath = msg.getStringProperty("filePath");
			Serializer out = proc.newSerializer(new File(filePath + ".html"));
			out.setOutputProperty(Serializer.Property.METHOD, "xml");
			out.setOutputProperty(Serializer.Property.INDENT, "yes");
			out.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION,
					"yes");
			XQueryExecutable exp;

			exp = comp.compile(new File("/opt/jboss-5.1.0.GA/upload/book.xq"));

			StreamSource ss = new StreamSource(new File(om.getObject()
					.toString()));
			XQueryEvaluator qe = exp.load();
			qe.setSource(ss);
			qe.run(out);
		} catch (SaxonApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
